package com.glory.brepda.utils;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.glory.brepda.R;

import java.util.List;

public class SearchPopupWindow extends PopupWindow {
    private EditText etSearch;
    private RecyclerView recyclerView;
    private SearchAdapter adapter;

    public SearchPopupWindow(Context context, List<String> dataList, View anchorView, View widthView, OnSelectListener listener) {
        super(context);

        View view = LayoutInflater.from(context).inflate(R.layout.popup_search_dropdown, null);
        setContentView(view);

        // ✅ 设置宽度与 anchorView 一致
        setWidth(widthView.getWidth());
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setFocusable(true);
        setOutsideTouchable(true);
        setBackgroundDrawable(new ColorDrawable());

        EditText etSearch = view.findViewById(R.id.etSearch);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));

        SearchAdapter adapter = new SearchAdapter(dataList, item -> {
            listener.onSelected(item);
            dismiss();
        });
        recyclerView.setAdapter(adapter);

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.filter(s.toString());
            }
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void afterTextChanged(Editable s) {}
        });

        adapter.filter("");
        showAsDropDown(anchorView);
    }


    public interface OnSelectListener {
        void onSelected(String selected);
    }
}

